/*
 * Create:      柿子
 * CreateDate:  2022/10/21
 * Describe：   汇总打印 - 处方单
 * */
import React, { Component } from 'react';
import { Row, Col, Button, Checkbox, message } from 'antd';
import { $loadTemplate } from 'pages/lodop/Common/Print.js';
import store from 'store';
import AcBarcode from 'ac-barcode';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import './style/index.less';

class PrescriptionPrinting extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    let currentPatData = React.$getSessionData('titleData');
    let patientData = React.$getSessionData('patientData');
    this.state = {
      userData,
      patientData,
      currentPatData,
      printData: [],
      resultTotalWidth: 550,
      resultColumns: [],
      prescriptionColumns: [],
      prescriptionTotalWidth: 650
    };

    // 检验结果
    this.staticResultsColumns = [{
      key: 1,
      title: '',
      dataIndex: 'eyePart',
      align: 'center',
      width: 80
    }, {
      key: 2,
      title: '裸眼视力',
      dataIndex: 'nakedVision',
      align: 'center',
      width: 80
    }, {
      key: 3,
      title: '球面镜',
      dataIndex: 'sphericalMirror',
      align: 'center',
      width: 80
    }, {
      key: 4,
      title: '柱镜',
      dataIndex: 'columnMirror',
      align: 'center',
      width: 80
    }, {
      key: 5,
      title: '轴位',
      dataIndex: 'axialPosition',
      align: 'center',
      width: 80
    }, {
      key: 6,
      title: '最佳矫正视力',
      dataIndex: 'correctedVision',
      align: 'center',
      width: 150
    }];

    // 处方
    this.staticPrescriptionsColumns = [{
      key: 1,
      title: '',
      dataIndex: 'type',
      align: 'center',
      width: 100
    }, {
      key: 2,
      title: '',
      dataIndex: 'eyePart',
      align: 'center',
      width: 80
    }, {
      key: 3,
      title: '球面镜',
      dataIndex: 'sphericalMirror',
      align: 'center',
      width: 80
    }, {
      key: 4,
      title: '柱镜',
      dataIndex: 'columnMirror',
      align: 'center',
      width: 80
    }, {
      key: 5,
      title: '轴位',
      dataIndex: 'axialPosition',
      align: 'center',
      width: 80
    }, {
      key: 6,
      title: '棱镜',
      dataIndex: 'prism',
      align: 'center',
      width: 80
    }, {
      key: 7,
      title: '棱镜底',
      dataIndex: 'prismBase',
      align: 'center',
      width: 80
    }, {
      key: 8,
      title: '矫正视力',
      dataIndex: 'correctedVision',
      align: 'center',
      width: 150
    }]
  }

  componentDidMount() {
    this.getPrintData();
    this.getResultsColumns();
    this.getPrescriptionColumns();
  }

  // 获取验光单数据
  getPrintData = async () => {
    try {
      let { currentPatData, patientData } = this.state;
      let data = {
        params: [{
          admID: currentPatData?.admID || patientData?.admID || ''
        }]
      }
      // let res = await React.$asyncPost(this, '17030074', data);
      let res = await React.$asyncPost(this, '17030078', data);
      let printData = res?.result || [];
      for (var i = 0; i < printData.length; i++) {
        printData[i].checked = true;
        let optometryObj = printData[i]?.optometryObj || {};
        printData[i].inspectionResultsData = printData[i]?.inspectionResultsData || [{ // 屈光检查结果
          key: 1,
          eyePart: '右眼', // 眼别
          nakedVision: optometryObj?.ComboBox2 || '', // 裸眼视力
          sphericalMirror: optometryObj?.field1 || '', // 球面镜
          columnMirror: optometryObj?.field2 || '', // 柱镜
          axialPosition: optometryObj?.field3 || '', // 轴位
          correctedVision: optometryObj?.ComboBox7 || '', // 最佳矫正视力
        }, {
          key: 2,
          eyePart: '左眼', // 眼别
          nakedVision: optometryObj?.ComboBox9 || '', // 裸眼视力
          sphericalMirror: optometryObj?.field6 || '', // 球面镜
          columnMirror: optometryObj?.field7 || '', // 柱镜
          axialPosition: optometryObj?.field8 || '', // 轴位
          correctedVision: optometryObj?.ComboBox8 || '', // 最佳矫正视力
        }];
        printData[i].prescriptionData = printData[i]?.prescriptionData || [{ // 配镜处方
          key: 1,
          type: '远用^Distance', // 类型
          eyePart: '右眼', // 眼别
          sphericalMirror: optometryObj?.field11 || '', // 球面镜
          columnMirror: optometryObj?.field13 || '', // 柱镜
          axialPosition: optometryObj?.field14 || '', // 轴位
          prism: optometryObj?.field15 || '', // 棱镜
          prismBase: optometryObj?.field16 || '', // 棱镜底
          correctedVision: optometryObj?.ComboBox3 || '', // 矫正视力
        }, {
          key: 2,
          type: '远用^Distance', // 类型
          eyePart: '左眼', // 眼别
          sphericalMirror: optometryObj?.field17 || '', // 球面镜
          columnMirror: optometryObj?.field18 || '', // 柱镜
          axialPosition: optometryObj?.field19 || '', // 轴位
          prism: optometryObj?.field20 || '', // 棱镜
          prismBase: optometryObj?.field21 || '', // 棱镜底
          correctedVision: optometryObj?.ComboBox4 || '', // 矫正视力
        }, {
          key: 3,
          type: '近用^Near', // 类型
          eyePart: '右眼', // 眼别
          sphericalMirror: optometryObj?.field23 || '', // 球面镜
          columnMirror: optometryObj?.field24 || '', // 柱镜
          axialPosition: optometryObj?.field25 || '', // 轴位
          prism: optometryObj?.field26 || '', // 棱镜
          prismBase: optometryObj?.field27 || '', // 棱镜底
          correctedVision: optometryObj?.ComboBox5 || '', // 矫正视力
        }, {
          key: 4,
          type: '近用^Near', // 类型
          eyePart: '左眼', // 眼别
          sphericalMirror: optometryObj?.field28 || '', // 球面镜
          columnMirror: optometryObj?.field29 || '', // 柱镜
          axialPosition: optometryObj?.field30 || '', // 轴位
          prism: optometryObj?.field31 || '', // 棱镜
          prismBase: optometryObj?.field32 || '', // 棱镜底
          correctedVision: optometryObj?.ComboBox6 || '', // 矫正视力
        }];
        // let ordArr = printData[i]?.ordArr || [];
        // for (var j = 0; j < ordArr.length; j++) { // 产品
        //   let ordItem = printData[i].ordArr[j];
        //   printData[i].ordArr[j] = {
        //     ...ordItem,
        //     ...(ordItem?.priceObj || {}),
        //     key: j + 1
        //   }
        // }
      }
      this.setState({ printData });
    } catch (error) {
      this.setState({ printData: [] });
    }
  }

  // 打印勾选
  handleCheckboxChange = (e, index) => {
    let { printData } = this.state;
    printData[index].checked = e.target.checked;
    this.setState({});
  }

  // 获取检验结果表头数据
  getResultsColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OptometrySheetResults',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let resultColumns = res?.result?.C || [];
      if (resultColumns && resultColumns.length > 0) {
        this.setState({
          resultColumns,
          resultTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取配镜处方表头数据
  getPrescriptionColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OptometrySheetprescription',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let prescriptionColumns = res?.result?.C || [];
      if (prescriptionColumns && prescriptionColumns.length > 0) {
        prescriptionColumns = prescriptionColumns.map(item => {
          return {
            ...item,
            render: (text, row, index) => {
              console.log("index", index)
              if (item.dataIndex === 'type') {
                let splitArr = text && text.indexOf('^') > -1 ? text.split('^') : [text]
                const obj = {
                  children: (
                    <div style={{ textAlign: 'center' }}>
                      {splitArr && splitArr.map((item, index) => {
                        return (
                          <div key={index}>{item}</div>
                        )
                      })}
                    </div>
                  ),
                  props: {},
                };
                if (index % 2 === 0) {
                  obj.props.rowSpan = 2;
                }
                if (index % 2 === 1) {
                  obj.props.rowSpan = 0;
                }
                return obj;
              } else {
                return (
                  <span>{text}</span>
                )
              }
            },
          }
        })
        this.setState({
          prescriptionColumns,
          prescriptionTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 打印
  handlePrint = async () => {
    try {
      let { printData } = this.state;
      let patOptometryRecordIDArr = [];
      for (var i = 0; i < printData.length; i++) {
        if (printData[i].checked) {
          patOptometryRecordIDArr.push(printData[i].patOptometryRecordID);
        }
      }
      if (!(patOptometryRecordIDArr && patOptometryRecordIDArr.length > 0)) {
        message.error('请选择需要打印的数据');
        return;
      }
      let data = {
        params: [{
          patOptometryRecordIDArr,
          prescFlag: 'Y'
        }]
      }
      // let res = await React.$asyncPost(this, '17030076', data);
      let res = await React.$asyncPost(this, '17030079', data);
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loadTemplate(item.template, item.printStr);
      });
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    const { userData, printData, resultTotalWidth, resultColumns, prescriptionColumns, prescriptionTotalWidth } = this.state;
    return (
      <div className="optometry-sheet">
        <div style={{ textAlign: 'right', marginBottom: 12 }}>
          <Button type="primary" onClick={this.handlePrint}>打印</Button>
        </div>
        <div className="scroll-bar-style" style={{ height: store.getState().tableHeight.y + 70 + 'px', overflow: 'auto', paddingRight: 100 }}>
          {printData && printData.map((item, index) => {
            let optometryObj = item?.optometryObj || {};
            let patObj = item?.patObj || {};
            let requestObj = item?.requestObj || {};
            return (
              <div key={index} className="os-print-item">
                <div className="os-ac-bar-code">
                  {patObj.patNo ? <AcBarcode value={patObj.patNo} width={1.5} height={32} fontSize={14} margin={3} /> : ''}
                </div>
                <h3 className="os-hosp">{requestObj?.hospDesc || userData?.hospDesc}</h3>
                <h1 className="os-title">
                  处 方 单
                  {/* <span className="os-title-status">未打印</span> */}
                  <div className="os-title-print">
                    <Checkbox checked={item.checked} onChange={(e) => this.handleCheckboxChange(e, index, item)}>打印</Checkbox>
                  </div>
                </h1>
                <Row className="os-item-rows">
                  <Col span={8}>
                    <span>姓名：</span>{patObj?.patName || ''}
                  </Col>
                  <Col span={6}>
                    <span>性别：</span>{patObj?.patSexDesc || ''}
                  </Col>
                  <Col span={10}>
                    <span>验光单号：</span>{optometryObj?.optometryNo || ''}
                  </Col>
                </Row>
                <Row className="os-item-rows">
                  <Col span={8}>
                    <span>出生年月：</span>{patObj?.patBirthDate || ''}
                  </Col>
                  <Col span={6}>
                    <span>眼位：</span>
                  </Col>
                  <Col span={10}>
                    <span>主视眼检查：</span>
                  </Col>
                </Row>
                <Row className="os-item-rows">
                  <Col span={8}>
                    <span>验光状态：</span>{optometryObj?.optometryType || ''}
                  </Col>
                  <Col span={6}>
                    <span>病族史：</span>{patObj?.familyHistory || ''}
                  </Col>
                  <Col span={10}>
                    <span>转科：</span>
                  </Col>
                </Row>
                <Row className="os-item-rows">
                  <Col span={8}>
                    <span>散瞳药物：</span>{optometryObj?.ComboBox12 || ''}
                  </Col>
                  <Col span={6}>
                    <span>眼别：</span>
                  </Col>
                </Row>
                <Row className="os-item-rows">
                  <Col span={8} style={{ fontWeight: 900, color: '#000' }}>
                    屈 光 检 查 结 果
                  </Col>
                  <Col span={6}>
                    <span>接诊医生：</span>{requestObj?.docDesc || ''}
                  </Col>
                  <Col span={10}>
                    <span>分店：</span>{requestObj?.hospDesc || ''}
                  </Col>
                </Row>
                <div style={{ minHeight: '100px' }}>
                  <PublicTablePagination
                    param={{
                      y: 'N',
                      height: 'auto',
                      x: resultTotalWidth,
                      data: item?.inspectionResultsData || [],
                      componentName: 'OptometrySheetResults',
                      columns: resultColumns && resultColumns.length > 0 ? resultColumns : this.staticResultsColumns,
                    }}
                    getColumns={this.getResultsColumns}
                  />
                </div>
                <Row>
                  <Col span={6}>
                    <span style={{ paddingLeft: 12 }}>ADD：</span>{optometryObj?.field40 || ''}
                  </Col>
                  <Col span={18}>
                    <span>验光备注：</span>{optometryObj?.ComboBox10 || ''}
                  </Col>
                </Row>
                <Row className="os-item-rows">
                  <Col span={8} style={{ fontWeight: 900, color: '#000' }}>
                    配 镜 处 方
                  </Col>
                  <Col span={6}>
                    <span>报告日期：</span>{optometryObj?.field37 || ''}
                  </Col>
                  <Col span={10}>
                    <span>验光师：</span>{optometryObj?.field39 || ''}
                  </Col>
                </Row>
                <div style={{ minHeight: '100px' }}>
                  <PublicTablePagination
                    param={{
                      y: 'N',
                      height: 'auto',
                      x: prescriptionTotalWidth,
                      data: item?.prescriptionData || [],
                      componentName: 'OptometrySheetprescription',
                      columns: prescriptionColumns && prescriptionColumns.length > 0 ? prescriptionColumns : this.staticPrescriptionsColumns,
                    }}
                    getColumns={this.getPrescriptionColumns}
                  />
                </div>
                <div style={{ paddingLeft: 12 }}>
                  备注：{optometryObj?.ComboBox11 || ' '}
                </div>
                <Row>
                  <Col span={14}>
                    瞳孔距离（PD）:远用：<span>{optometryObj?.field35 || ''}</span>mn
                  </Col>
                  <Col span={10}>
                    近用：<span>{optometryObj?.field36 || ''}</span>mn
                  </Col>
                </Row>
                <Row>
                  <Col span={14}>
                    处方签发者：{optometryObj?.field39 || ''}
                  </Col>
                  <Col span={10}>
                    处方时间：<span>{optometryObj?.field37 || ''}</span>
                  </Col>
                </Row>
                <div style={{ display: optometryObj && optometryObj.correctivePlanDesc ? 'block' : 'none', marginTop: '6px' }}>
                  <div style={{ fontWeight: 900, color: '#000' }}>
                    {optometryObj?.correctivePlanDesc || ''}
                  </div>
                  {'correctivePlanStr' in optometryObj && optometryObj.correctivePlanStr && optometryObj.correctivePlanStr.indexOf('\\n') > -1 && optometryObj.correctivePlanStr.split('\\n').map((item, index) => {
                    return (
                      <div key={index}>
                        {item}
                      </div>
                    )
                  })}
                </div>
                <div className="os-footer">
                  <Row className="os-item-rows">
                    <Col span={14}>
                      网址：{requestObj?.hospWeb || ''}
                    </Col>
                    <Col span={10}>
                      电话：{requestObj?.hospPhone || ''}
                    </Col>
                  </Row>
                  <Row className="os-item-rows">
                    <Col span={14}>
                      地址：{requestObj?.hospAddress || ''}
                    </Col>
                    <Col span={10} style={{ textAlign: 'right', color: '#999' }}>
                      注：本处方仅供本院使用，外用仅供参考
                    </Col>
                  </Row>
                </div>
              </div>
            )
          })}
        </div>
      </div>
    )
  }
};

export default PrescriptionPrinting;